import type { ItemResult } from '@/types/search';

const hlStyleAdd = (html: string) => html.replaceAll("<mark>", `<mark class="text-yellow-300 bg-transparent font-bold">`)

const parsePagefindResults2ItemResult = (results: CustomPagefindTypes.SearchResult<ItemResult>[]): ItemResult[] => {
  // @ts-expect-error: type is validate for result, don't know why it said:
  // "exampleA" | "exampleB" could't convert to "exampleA"
  return results.map(({ excerpt, raw_url, meta: { id, title, type } }) => process.env.NODE_ENV === 'development' ? ({
    id,
    type,
    title,
    subTitle: hlStyleAdd(excerpt),
    link: raw_url,
  }) : ({
    id: raw_url,
    type,
    title,
    subTitle: hlStyleAdd(excerpt),
    link: raw_url,
  }))
}

export default async function getResultByPagefind(keyword: string) {
  // 跳过 SSG 渲染静态页面时的执行
  if (!globalThis.document) {
    return {
      async search() { return { results: { hits: [] } } }
    }
  }

  // eslint-disable-next-line no-undef
  const pagefindJsPath = process.env.NODE_ENV === 'development' ? '/.cache/pagefind/lib/pagefind.js' : 'pagefind/pagefind.js'

  // no pagefind instance in types!!!
  // ignore it because this is runtime only
  const pagefind = await import(
    pagefindJsPath
  )
  const { results } = await pagefind.search(keyword)
  const data = await Promise.all(results.map(async (v) => await v.data()))
  const hits: ItemResult[] = parsePagefindResults2ItemResult(data)

  return {
    results: [
      {
        hits,
      }
    ]
  }
}